<?php
session_start();
if(!isset($_SESSION)) die("you want logging");
require_once "configure.php";

if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}



//Vérifier les paramèttres
if(empty($_GET['id_key']) or empty($_GET['id_lang']) or empty($_GET['type']) ){
	die("Fatal Error!");
	exit;
}
//Vérifier les champs
if($_GET['type']=="update" && (empty($_GET['translation']) or empty($_GET['id_status']) )){
	die("Fatal Error!");
	exit();
}
	
//Connexion à la base de données
$connect = mysql_connect(DB_SERVEUR,DB_USER,DB_PASS);
@mysql_query("SET NAMES 'utf8'");
@mysql_query("SET CHARACTER SET utf8");
mysql_select_db(DB_BDD) or die("erreur de connexion a la base de donnees");
//Valider l'action
$sql_isvalid="SELECT id_status, translation , id_key, id_user_trans
			  FROM translation 
			  WHERE id_key=".$_GET['id_key']." 
			  AND id_lang=".$_GET['id_lang'].";";
$SqlStr= mysql_query($sql_isvalid) or die(mysql_error());

$rows = mysql_fetch_row ($SqlStr);
$type=$_GET['type'];

//Vérifier l'action
if(($type=="update" && $rows[0]==0) || ( ($type=="validate" || $type=="refused") && $rows[0]==1 ) || ( $type=="reset" && $rows[0]==2 ) || ($type=="reject" && $rows[0]==1) ){
	//Get key_name US
	$sql_get_duplicate="SELECT t.`translation` 
						 FROM `translation` t
						 JOIN `keys` as k on k.`id_key`=t.`id_key`
						  WHERE t.`id_lang`=1 
						  AND t.`id_key`=".$_GET['id_key'];
	if($type=='reset'){
		$sql_get_duplicate.=" AND k.`key_name`='".mysql_real_escape_string($_GET['keyname'])."' ";	
	}

	$rs_get_duplicate= mysql_query($sql_get_duplicate) or die(mysql_error());
	$rows_get_duplicate = mysql_fetch_row ($rs_get_duplicate);
				  
	//Trouver les keys identiques
	$select_all_idem="SELECT t.`id_key` 
					  FROM `translation` t
					  JOIN `keys` AS k ON k.`id_key`=t.`id_key`
					  WHERE t.`id_lang`=1 
					  AND t.`translation` ='".mysql_real_escape_string($rows_get_duplicate[0])."'";
	
	if($type=='reset'){
		$select_all_idem.=" AND k.`key_name`='".mysql_real_escape_string($_GET['keyname'])."' ";	
	}
	
	@mysql_query("SET NAMES 'utf8'");
	@mysql_query("SET CHARACTER SET utf8");
	$SqlStr = mysql_query($select_all_idem);
	$i=0;
	while ($rang=mysql_fetch_array($SqlStr)){
		if($i==0){
			$MarqueId = $rang['id_key'];
		}else{
			$MarqueId.=",".$rang['id_key'];
		}
		$i++;
	}
	
	if($MarqueId=="," || $MarqueId=="")
		$MarqueId=$_GET['id_key'];
	
	// Construction requête en fonction le type d'action
	switch($type){					
		case 'update':
			$sql = 'UPDATE `translation` ';
			$sql .= ' SET `translation`.`translation`=REPLACE("' .(utf8_encode($_GET['translation']));
			$sql .= '","%u","&#x") , `translation`.`date`=NOW(), `translation`.`id_status`='.intval($_GET['id_status']);
			if(intval($rows[3])==0){					
				$sql .= ' , `translation`.`id_user_trans`='.intval($_SESSION['id_user']->id_user);
			}else{
				$sql .= ' , `translation`.`id_editor`='.intval($_SESSION['id_user']->id_user);
			}
			$sql .= ' WHERE `translation`.`id_key` IN ('.$MarqueId.')';
			$sql .= ' AND `translation`.`id_lang`='.intval($_GET['id_lang']);
			$sql .= ' AND `translation`.`id_status`!=2 ';

			break;				
			
		case 'reset':
		case 'refused':
		case 'validate':
			$sql = 'UPDATE translation ';
			$sql .= ' SET id_status='.intval($_GET['id_status']);
			if($type=='reset')
				$sql .= ' , id_user_validate=0';

			if($type=='validate')
				$sql .= ' , id_user_validate='.intval($_SESSION['id_user']->id_user);
				
			$sql .= ' WHERE id_key IN ('.$MarqueId.')';
			if(($type=='reset' && $_GET['id_lang']!=1) || $type!='reset'){
				$sql .= ' AND id_lang='.intval($_GET['id_lang']);
			}
			if($type=='reset')
				$sql .=' AND id_status=2 ';
				
			break;
			
		case 'reject':
			$sql = 'UPDATE translation ';
			$sql .= ' SET id_status=0';
			$sql .= ' , id_user_trans=0';
			$sql .= ' , id_user_validate=0';
			$sql .= ' , id_editor=0';
			$sql .= " , translation='', date='0000-00-00 00:00:00'";			
			$sql .= ' WHERE id_key IN ('.$MarqueId.')';
			$sql .= ' AND id_lang='.intval($_GET['id_lang']);		
			break;
						
		default:
			exit;
	}
	//echo $sql;
	// Exécution ... requête
	@mysql_query("SET NAMES 'utf8'");
	@mysql_query("SET CHARACTER SET utf8");
	mysql_query($sql) or die(mysql_error());
	mysql_close();
	die("nothing");
}else{
	//En cas d'erreur
	$sql_When_Error="SELECT t.id_status, t.translation, u.email 
					 FROM translation t
					 LEFT JOIN users as u ON t.id_user_trans=u.id_user
					 WHERE t.id_key=".$_GET['id_key']." 
					 AND t.id_lang=".$_GET['id_lang'].";";
	$SqlStrWhenError= mysql_query($sql_When_Error) or die(mysql_error());	
	$rowsWhenError = mysql_fetch_row ($SqlStrWhenError);		
	mysql_close();
	die(json_encode($rowsWhenError));		
}
	
?>